@page "/database-chat"
@page "/database-chat/{ConnectionId}"
@using Text2Sql.Net.Domain.Interface
@using Text2Sql.Net.Repositories.Text2Sql.DatabaseConnection
@using Text2Sql.Net.Repositories.Text2Sql.ChatHistory
@using AntDesign
@inject IDatabaseConnectionConfigRepository DatabaseConnectionRepository
@inject IChatService ChatService
@inject ISqlExecutionService SqlExecutionService
@inject MessageService MessageService
@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager

<PageContainer Title="Text2Sql">
    <Content>
        <Card>
            <div class="database-chat-container">
                <div class="database-selection">
                    <Select TItem="DatabaseConnectionConfig"
                            TItemValue="string"
                            DataSource="@_connections"
                            @bind-Value="@_selectedConnectionId"
                            ValueName="@nameof(DatabaseConnectionConfig.Id)"
                            LabelName="@nameof(DatabaseConnectionConfig.Name)"
                            Style="width: 100%;"
                            Placeholder="请选择数据库连接"
                            OnSelectedItemChanged="OnDatabaseSelected"
                            Disabled="@_loading">
                    </Select>
                </div>

                <div class="chat-history-container" @ref="_chatContainerRef">
                    @if (_loadingHistory)
                    {
                        <div class="loading-container">
                            <Spin Tip="正在加载聊天历史..." />
                        </div>
                    }
                    else if (_chatHistory != null && _chatHistory.Count > 0)
                    {


                        <AntList TItem="ChatMessage"
                                 DataSource="_chatHistory"
                                 ItemLayout="ListItemLayout.Horizontal"
                                 Context="message">

                            <ListItem>
                                <Card Bordered="false" Class="@(message.IsUser ? "user-message" : "assistant-message")">
                                    <div class="message-header">
                                        <strong>@(message.IsUser ? "帅小伙" : "AI")</strong>
                                        <span class="message-time">@message.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")</span>
                                    </div>
                                    <div class="message-content">
                                        @message.Message
                                    </div>
                                    @if (!message.IsUser && !string.IsNullOrEmpty(message.SqlQuery))
                                    {
                                        <div class="sql-content">
                                            <Divider Orientation="left">生成的SQL</Divider>
                                            <pre class="language-sql">@message.SqlQuery</pre>
                                            <div class="sql-actions">
                                                <Button Type="@ButtonType.Link" OnClick="async () => await CopySqlToClipboard(message.SqlQuery)">
                                                    <Icon Type="copy" /> 复制
                                                </Button>
                                                <Button Type="@ButtonType.Link" OnClick="async () => await ExecuteSqlAsync(message.SqlQuery)">
                                                    <Icon Type="play-circle" /> 执行
                                                </Button>
                                                @if (message.QueryResult != null && message.QueryResult.Count > 0)
                                                {
                                                    <Button Type="@ButtonType.Link" OnClick="async () => await ShowChartForMessage(message)">
                                                        <Icon Type="bar-chart" /> 查看图表
                                                    </Button>
                                                    <Tag Color="green" Style="margin-left: 8px;">
                                                        <Icon Type="check-circle" /> 已自动执行 (@(message.QueryResult.Count) 条)
                                                    </Tag>
                                                }
                                            </div>
                                            @if (!string.IsNullOrEmpty(message.ExecutionError))
                                            {
                                                <Alert Type="@AlertType.Error" Message="执行错误" Description="@message.ExecutionError" ShowIcon="true" />
                                            }
                                        </div>
                                    }
                                    @if (!message.IsUser && message.QueryResult != null && message.QueryResult.Count > 0)
                                    {
                                        <div class="query-result-content">
                                            <Divider Orientation="left">查询结果</Divider>
                                            <div class="result-info">
                                                <Space>
                                                    <SpaceItem>
                                                        <Tag Color="blue">@(message.QueryResult.Count) 条记录</Tag>
                                                    </SpaceItem>
                                                </Space>
                                            </div>
                                            <div class="inline-table-container">
                                                <Table TItem="Dictionary<string, object>"
                                                       DataSource="@message.QueryResult"
                                                       Bordered
                                                       Size="@TableSize.Small"
                                                       ScrollX="600"
                                                       ScrollY="300"
                                                       PageSize="10">
                                                    <ChildContent Context="tableRowData">
                                                        @{
                                                            var columns = message.QueryResult.FirstOrDefault()?.Keys.ToList() ?? new List<string>();
                                                        }
                                                        @foreach (var column in columns)
                                                        {
                                                            <AntDesign.Column TData="Dictionary<string, object>" Title="@column" Width="120">
                                                                @(tableRowData[column]?.ToString() ?? "")
                                                            </AntDesign.Column>
                                                        }
                                                    </ChildContent>
                                                </Table>
                                            </div>
                                        </div>
                                    }
                                </Card>
                            </ListItem>

                        </AntList>

                    }
                    else
                    {
                        <Empty Description=@("暂无聊天记录") />
                    }
                </div>

                <div class="chat-input-container">
                    <div class="input-header-actions">
                        <Button Type="@ButtonType.Text"
                                Danger="true"
                                OnClick="@ShowClearConfirm"
                                Disabled="@(_selectedConnectionId == null || _chatHistory?.Count == 0)"
                                Icon="delete">
                            清空聊天记录
                        </Button>
                    </div>
                    
                    <div class="input-group-container">
                        <TextArea @bind-Value="@_userMessage"
                                  Placeholder="请输入数据库相关问题，例如：查询所有用户信息"
                                  AutoSize="true"
                                  OnPressEnter="@SendMessage"
                                  Disabled="@(_selectedConnectionId == null || _loading)"
                                  Class="message-input" />
                        
                        <Button Type="@ButtonType.Primary"
                                OnClick="@SendMessage"
                                Loading="@_loading"
                                Class="send-button"
                                Icon="send">
                            发送
                        </Button>
                    </div>

                    @if (_loading)
                    {
                        <div class="loading-hint">
                            <Spin Size="small" /> <span>正在处理您的请求，可能需要几秒钟时间...</span>
                        </div>
                    }
                </div>
            </div>
        </Card>
    </Content>
</PageContainer>



<Modal Title="图表预览"
       Visible="@_isChartModalVisible"
       OnOk="@OnChartOk"
       OnCancel="@OnChartCancel"
       Style="width:95%;max-width:1400px;"
       Centered>
    
    <!-- 图表控制面板 -->
    <div class="chart-control-panel">
        <Row Gutter="16">
            <Col Span="8">
                <div class="control-group">
                    <label class="control-label">图表类型</label>
                    <Select TItem="ChartTypeOption"
                            TItemValue="string"
                            DataSource="@_chartTypes"
                            @bind-Value="@_selectedChartType"
                            ValueName="@nameof(ChartTypeOption.Key)"
                            LabelName="@nameof(ChartTypeOption.Label)"
                            Style="width: 100%;"
                            OnSelectedItemChanged="@((chartType) => OnChartTypeChanged(chartType))">
                        <ItemTemplate Context="chartType">
                            <Icon Type="@chartType.Icon" Style="margin-right: 8px;" />
                            @chartType.Label
                        </ItemTemplate>
                    </Select>
                </div>
            </Col>
            <Col Span="8">
                <div class="control-group">
                    <label class="control-label">分类字段</label>
                    <Select TItem="ColumnOption"
                            TItemValue="string"
                            DataSource="@_availableColumns"
                            @bind-Value="@_selectedCategoryColumn"
                            ValueName="@nameof(ColumnOption.Key)"
                            LabelName="@nameof(ColumnOption.Label)"
                            Style="width: 100%;"
                            OnSelectedItemChanged="@((column) => OnColumnSelectionChanged(column))">
                    </Select>
                </div>
            </Col>
            <Col Span="8">
                <div class="control-group">
                    <label class="control-label">数值字段</label>
                    <Select TItem="ColumnOption"
                            TItemValue="string"
                            DataSource="@_availableColumns"
                            @bind-Values="@_selectedValueColumns"
                            ValueName="@nameof(ColumnOption.Key)"
                            LabelName="@nameof(ColumnOption.Label)"
                            Mode="multiple"
                            Style="width: 100%;"
                            OnSelectedItemsChanged="@((columns) => OnValueColumnsChanged(columns))">
                    </Select>
                </div>
            </Col>
        </Row>
        
        <div class="chart-tips">
            <Icon Type="info-circle" Style="color: #1890ff; margin-right: 4px;" />
            <span>提示：饼图仅支持单个数值字段，散点图需要至少两个数值字段</span>
        </div>
    </div>
    
    <!-- 图表显示区域 -->
    <div class="chart-display-area">
        <div id="chatChartContainer" style="width:100%;height:600px;min-height:600px;"></div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="chart-actions">
        <Space>
            <SpaceItem>
                <Button Type="@ButtonType.Default" OnClick="@ResetChartToAuto">
                    <Icon Type="reload" /> 重置为自动
                </Button>
            </SpaceItem>
            <SpaceItem>
                <Button Type="@ButtonType.Primary" OnClick="@ExportChartPng">
                    <Icon Type="download" /> 导出 PNG
                </Button>
            </SpaceItem>
        </Space>
    </div>
    
</Modal>

<Modal Title="确认清空"
       Visible="@_isClearConfirmVisible"
       OnOk="@ClearChatHistory"
       OnCancel="@(() => _isClearConfirmVisible = false)"
       ConfirmLoading="@_clearingHistory"
       OkText="@("确认清空")"
       CancelText="@("取消")">
    <p>确定要清空当前数据库连接的所有聊天记录吗？</p>
    <p style="color: #ff4d4f; font-size: 12px;">此操作不可撤销</p>
</Modal>

<style>
    .database-chat-container {
        display: flex;
        flex-direction: column;
        height: 1000px;
        gap: 16px;
        position: relative;
    }

    .database-selection {
        margin-bottom: 16px;
    }

    .chat-history-container {
        flex-grow: 1;
        overflow-y: auto;
        margin-bottom: 16px;
        padding-right: 8px;
        transition: all 0.3s ease;
    }

    .chat-history-container.collapsed {
        max-height: 40px;
        overflow: hidden;
    }

    .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;
    }

    .chat-input-container {
        position: sticky;
        bottom: 0;
        width: 100%;
        background-color: white;
        padding-top: 8px;
        border-top: 1px solid #f0f0f0;
        margin-top: auto;
    }

    .input-header-actions {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 8px;
        padding-bottom: 8px;
        border-bottom: 1px solid #f0f0f0;
    }

    .input-group-container {
        display: flex;
        gap: 8px;
        align-items: flex-start;
        width: 100%;
    }

    .message-input {
        flex: 1;
        min-height: 32px;
    }

    .send-button {
        flex-shrink: 0;
        height: auto;
        min-height: 32px;
        display: flex;
        align-items: center;
    }

    .user-message {
        width: 100%;
        background-color: #e6f7ff;
        margin-left: 20%;
        margin-right: 0;
        border-radius: 8px;
        animation: fadein 0.3s ease-in;
    }

    .assistant-message {
        background-color: #f6f6f6;
        margin-right: 20%;
        margin-left: 0;
        border-radius: 8px;
        animation: fadein 0.3s ease-in;
    }

    @@keyframes fadein {
        from {
            opacity: 0;
            transform: translateY(10px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .message-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
    }

    .message-time {
        font-size: 12px;
        color: #999;
    }

    .message-content {
        white-space: pre-wrap;
        word-break: break-word;
    }

    .sql-content {
        margin-top: 12px;
        background-color: #f9f9f9;
        padding: 12px;
        border-radius: 6px;
        border-left: 3px solid #1890ff;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

        .sql-content pre {
            margin: 0;
            white-space: pre-wrap;
            max-height: 300px;
            overflow: auto;
            background-color: #282c34 !important;
            padding: 12px;
            border-radius: 6px;
            font-family: 'Fira Code', 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.5;
            border: 1px solid #e1e1e1;
            position: relative;
        }

        .sql-content pre.language-sql {
            background-color: #282c34 !important;
            color: #abb2bf !important;
        }

        /* 强制覆盖Prism.js默认样式 - SQL关键词高亮 */
        .sql-content .token.keyword,
        .sql-content pre.language-sql .token.keyword,
        pre.language-sql .token.keyword {
            color: #ff6b6b !important;
            font-weight: 900 !important;
            text-transform: uppercase !important;
            background-color: rgba(255, 107, 107, 0.15) !important;
            padding: 2px 4px !important;
            border-radius: 3px !important;
            text-shadow: 0 0 2px rgba(255, 107, 107, 0.3) !important;
            letter-spacing: 0.5px !important;
            display: inline-block !important;
        }

        /* 特别突出显示主要SQL关键词 */
        .sql-content .token.keyword.sql-primary,
        .sql-content pre.language-sql .token.keyword.sql-primary,
        pre.language-sql .token.keyword.sql-primary {
            color: #fff !important;
            background-color: #ff6b6b !important;
            font-weight: 900 !important;
            padding: 3px 6px !important;
            border-radius: 4px !important;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
            box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3) !important;
            display: inline-block !important;
        }

        /* 确保SQL代码块内所有关键词都被正确识别 */
        .sql-content pre code .token.keyword,
        pre.language-sql code .token.keyword {
            color: #ff6b6b !important;
            font-weight: 900 !important;
            text-transform: uppercase !important;
        }

        /* 后备高亮方案的样式 */
        .sql-content .sql-keyword-fallback,
        pre .sql-keyword-fallback {
            color: #fff !important;
            font-weight: 900 !important;
            padding: 2px 4px !important;
            border-radius: 3px !important;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
            display: inline-block !important;
            margin: 1px !important;
        }

        .sql-content .token.string {
            color: #98c379 !important;
        }

        .sql-content .token.number {
            color: #d19a66 !important;
        }

        .sql-content .token.operator {
            color: #56b6c2 !important;
        }

        .sql-content .token.function {
            color: #61afef !important;
        }

        .sql-content .token.comment {
            color: #5c6370 !important;
            font-style: italic;
        }

        /* 滚动条样式优化 */
        .sql-content pre::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        .sql-content pre::-webkit-scrollbar-track {
            background: #3a3f4b;
            border-radius: 4px;
        }

        .sql-content pre::-webkit-scrollbar-thumb {
            background: #5c6370;
            border-radius: 4px;
        }

        .sql-content pre::-webkit-scrollbar-thumb:hover {
            background: #6c7b7f;
        }

    .query-result-content {
        margin-top: 12px;
        background-color: #fafafa;
        padding: 12px;
        border-radius: 6px;
        border-left: 3px solid #52c41a;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .inline-table-container {
        margin-top: 8px;
        background-color: white;
        border-radius: 6px;
        overflow: hidden;
        border: 1px solid #f0f0f0;
    }

        .inline-table-container .ant-table {
            margin-bottom: 0;
        }

        .inline-table-container .ant-table-thead > tr > th {
            background-color: #fafafa;
            font-weight: 600;
            border-bottom: 2px solid #f0f0f0;
        }

        .inline-table-container .ant-table-tbody > tr > td {
            padding: 8px 12px;
            border-bottom: 1px solid #f5f5f5;
            word-break: break-word;
            max-width: 200px;
        }

        .inline-table-container .ant-table-tbody > tr:hover > td {
            background-color: #f5f5f5;
        }

        .inline-table-container .ant-pagination {
            margin: 12px 0 0 0;
            text-align: center;
        }

    .sql-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 8px;
        gap: 8px;
        padding-top: 8px;
        border-top: 1px solid #e8e8e8;
    }

        .sql-actions .ant-btn-link {
            padding: 4px 8px;
            height: auto;
            color: #1890ff;
            transition: all 0.3s ease;
        }

        .sql-actions .ant-btn-link:hover {
            background-color: rgba(24, 144, 255, 0.1);
            border-radius: 4px;
        }

        .sql-actions .ant-btn-link .anticon {
            margin-right: 4px;
        }

    .result-info {
        margin-bottom: 8px;
    }

    .loading-hint {
        margin-top: 8px;
        font-size: 12px;
        color: #999;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    ::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    ::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
    }

        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

    /* 图表控制面板样式 */
    .chart-control-panel {
        background: #fafafa;
        border: 1px solid #f0f0f0;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 16px;
    }

    .control-group {
        margin-bottom: 12px;
    }

    .control-label {
        display: block;
        font-weight: 500;
        color: #262626;
        margin-bottom: 4px;
        font-size: 14px;
    }

    .chart-tips {
        margin-top: 12px;
        padding: 8px 12px;
        background: #e6f7ff;
        border: 1px solid #91d5ff;
        border-radius: 4px;
        font-size: 12px;
        color: #0050b3;
        display: flex;
        align-items: center;
    }

    .chart-display-area {
        background: white;
        border: 1px solid #f0f0f0;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 16px;
        min-height: 640px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    #chatChartContainer {
        width: 100% !important;
        height: 600px !important;
        min-height: 600px !important;
    }

    .chart-actions {
        text-align: right;
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;
    }
</style>

@code {
    [Parameter]
    public string? ConnectionId { get; set; }

    private List<DatabaseConnectionConfig> _connections = new List<DatabaseConnectionConfig>();
    private string? _selectedConnectionId;
    private List<ChatMessage> _chatHistory = new List<ChatMessage>();
    private string? _userMessage;
    private bool _loading = false;
    private bool _loadingHistory = false;
    private ElementReference _chatContainerRef;
    private ChatMessage? _currentChartMessage;
    private bool _isChartModalVisible = false;
    private bool _isClearConfirmVisible = false;
    private bool _clearingHistory = false;

    // 图表控制相关变量
    private List<ChartTypeOption> _chartTypes = new List<ChartTypeOption>();
    private List<ColumnOption> _availableColumns = new List<ColumnOption>();
    private string _selectedChartType = "bar";
    private string? _selectedCategoryColumn;
    private IEnumerable<string> _selectedValueColumns = new List<string>();

    // 数据模型
    public class ChartTypeOption
    {
        public string Key { get; set; } = string.Empty;
        public string Label { get; set; } = string.Empty;
        public string Icon { get; set; } = string.Empty;
    }

    public class ColumnOption
    {
        public string Key { get; set; } = string.Empty;
        public string Label { get; set; } = string.Empty;
        public string Type { get; set; } = string.Empty;
    }

    protected override async Task OnInitializedAsync()
    {
        // 确保初始化时状态正确
        _loading = false;
        _loadingHistory = false;

        // 初始化图表类型选项
        InitializeChartTypes();

        try
        {
            await LoadDatabaseConnections();
            
            // 检查URL参数中的connectionId
            var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
            var queryParams = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query);
            string? connectionIdFromQuery = null;
            
            if (queryParams.TryGetValue("connectionId", out var connectionIdValues))
            {
                connectionIdFromQuery = connectionIdValues.FirstOrDefault();
            }
            
            // 优先使用路由参数，其次使用查询参数
            var targetConnectionId = !string.IsNullOrEmpty(ConnectionId) ? ConnectionId : connectionIdFromQuery;
            
            if (!string.IsNullOrEmpty(targetConnectionId))
            {
                _selectedConnectionId = targetConnectionId;
                var selectedConnection = _connections.FirstOrDefault(c => c.Id == targetConnectionId);
                if (selectedConnection != null)
                {
                    await OnDatabaseSelected(selectedConnection);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"加载数据库连接失败: {ex.Message}");
        }

        await base.OnInitializedAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        try
        {
            if (firstRender)
            {
                // 首次渲染后，等待更长时间确保Prism.js加载完成
                await Task.Delay(500);
                Console.WriteLine("开始初始化SQL高亮...");
                
                // 检查Prism.js是否加载
                var prismLoaded = await JSRuntime.InvokeAsync<bool>("eval", "typeof Prism !== 'undefined'");
                Console.WriteLine($"Prism.js加载状态: {prismLoaded}");
                
                if (prismLoaded)
                {
                    await JSRuntime.InvokeVoidAsync("databaseChatFunctions.highlightAllSql");
                    Console.WriteLine("SQL高亮已应用");
                }
                else
                {
                    Console.WriteLine("Prism.js未加载，尝试手动高亮");
                    // 尝试直接调用Prism
                    await JSRuntime.InvokeVoidAsync("eval", "if(typeof Prism !== 'undefined') { Prism.highlightAll(); }");
                }
            }
            else
            {
                // 每次重新渲染后重新应用SQL语法高亮
                await Task.Delay(200); // 等待DOM更新
                
                try
                {
                    await JSRuntime.InvokeVoidAsync("databaseChatFunctions.highlightAllSql");
                }
                catch
                {
                    // 如果自定义函数失败，尝试直接调用Prism
                    await JSRuntime.InvokeVoidAsync("eval", "if(typeof Prism !== 'undefined') { Prism.highlightAll(); }");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"SQL高亮处理失败: {ex.Message}");
        }

        await base.OnAfterRenderAsync(firstRender);
    }

    /// <summary>
    /// 加载数据库连接列表
    /// </summary>
    /// <returns>异步任务</returns>
    private async Task LoadDatabaseConnections()
    {
        try
        {
            _connections = await DatabaseConnectionRepository.GetListAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取数据库连接列表失败: {ex.Message}");
            _= MessageService.Error("获取数据库连接列表失败，请刷新页面重试");
            _connections = new List<DatabaseConnectionConfig>();
        }
    }

    /// <summary>
    /// 处理数据库选择事件
    /// </summary>
    /// <param name="connection">选中的数据库连接配置</param>
    /// <returns>异步任务</returns>
    private async Task OnDatabaseSelected(DatabaseConnectionConfig connection)
    {
        if (connection == null) return;

        try
        {
            // 设置加载状态
            _loadingHistory = true;

            try
            {
                _chatHistory = await ChatService.GetChatHistoryAsync(_selectedConnectionId!);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取聊天历史失败: {ex.Message}");
                _= MessageService.Error($"加载聊天历史失败: {ex.Message}");
                _chatHistory = new List<ChatMessage>();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"选择数据库连接失败: {ex.Message}");
            _= MessageService.Error($"选择数据库连接失败: {ex.Message}");
        }
        finally
        {
            _loadingHistory = false;

        }
    }

    /// <summary>
    /// 发送用户消息并获取AI响应
    /// </summary>
    /// <returns>异步任务</returns>
    private async Task SendMessage()
    {
        if (string.IsNullOrWhiteSpace(_userMessage) || _selectedConnectionId == null)
            return;

        // 避免重复发送
        if (_loading) return;

        string currentMessage = _userMessage;
        _userMessage = string.Empty;

        try
        {
            _loading = true;

            // 添加用户消息到聊天历史
            var userMessage = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    ConnectionId = _selectedConnectionId,
                    Message = currentMessage,
                    IsUser = true,
                    CreateTime = DateTime.Now
                };

            try
            {
                await ChatService.SaveChatMessageAsync(userMessage);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存用户消息失败: {ex.Message}");
                // 继续执行，即使保存失败
            }

            _chatHistory.Add(userMessage);


            // 生成并执行SQL
            var response = await ChatService.GenerateAndExecuteSqlAsync(_selectedConnectionId, currentMessage);

            // 如果执行出错，尝试优化SQL
            if (!string.IsNullOrEmpty(response.ExecutionError))
            {
                try
                {
                    _= MessageService.Info("SQL执行出错，尝试优化中...");


                    response = await ChatService.OptimizeSqlAndExecuteAsync(_selectedConnectionId, currentMessage, response.SqlQuery ?? string.Empty, response.ExecutionError);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"优化SQL失败: {ex.Message}");
                    // 优化失败，仍然使用原来的响应
                }
            }

            // 添加AI响应到聊天历史
            _chatHistory.Add(response);
            
            // 强制重新渲染以触发高亮
            StateHasChanged();

            // 如果生成了SQL，自动执行查询
            if (!string.IsNullOrEmpty(response.SqlQuery) && string.IsNullOrEmpty(response.ExecutionError))
            {
                try
                {
                    var (autoResult, autoError) = await SqlExecutionService.ExecuteQueryAsync(_selectedConnectionId, response.SqlQuery);
                    
                    if (!string.IsNullOrEmpty(autoError))
                    {
                        // 更新响应中的执行错误信息
                        response.ExecutionError = autoError;
                        // 更新数据库中的聊天记录
                        await ChatService.SaveChatMessageAsync(response);
                    }
                    else if (autoResult != null && autoResult.Count > 0)
                    {
                        // 更新响应中的查询结果
                        response.QueryResult = autoResult;
                        // 更新数据库中的聊天记录
                        await ChatService.SaveChatMessageAsync(response);
                        
                        // 查询结果已经保存在response.QueryResult中
                        
                        _= MessageService.Success($"SQL自动执行成功，返回 {autoResult.Count} 条记录");
                    }
                    else
                    {
                        _= MessageService.Info("SQL自动执行成功，但未返回数据");
                    }
                }
                catch (Exception autoEx)
                {
                    Console.WriteLine($"自动执行SQL失败: {autoEx.Message}");
                    // 不显示错误消息给用户，因为用户仍然可以手动执行
                }
            }
            
            // 查询结果已经在response中，界面会自动显示
        }
        catch (Exception ex)
        {
            Console.WriteLine($"处理消息失败: {ex.Message}");
            _= MessageService.Error($"处理请求时出错: {ex.Message}");

            // 如果是因为用户消息已经添加但处理失败，添加一个系统错误消息
            if (_chatHistory.Any(m => m.IsUser && m.Message == currentMessage && !_chatHistory.Any(r => !r.IsUser && r.CreateTime > m.CreateTime)))
            {
                _chatHistory.Add(new ChatMessage
                    {
                        Id = Guid.NewGuid().ToString(),
                        ConnectionId = _selectedConnectionId,
                        Message = $"处理您的请求时出现错误：{ex.Message}",
                        IsUser = false,
                        CreateTime = DateTime.Now
                    });
            }
        }
        finally
        {
            _loading = false;
        }
    }

    /// <summary>
    /// 执行SQL查询并显示结果
    /// </summary>
    /// <param name="sql">要执行的SQL查询语句</param>
    /// <returns>异步任务</returns>
    private async Task ExecuteSqlAsync(string sql)
    {
        if (string.IsNullOrWhiteSpace(sql) || _selectedConnectionId == null)
            return;

        // 避免重复执行
        if (_loading) return;

        try
        {
            _loading = true;

            var (result, errorMessage) = await SqlExecutionService.ExecuteQueryAsync(_selectedConnectionId, sql);

            if (!string.IsNullOrEmpty(errorMessage))
            {
                _= MessageService.Error($"SQL执行错误: {errorMessage}");
            }
            else if (result != null)
            {
                _= MessageService.Success($"SQL执行成功，返回 {result.Count} 条记录");
                // 结果会通过聊天消息显示，无需额外处理
            }
            else
            {
                _= MessageService.Info("SQL执行成功，但未返回数据");
            }
        }
        catch (Exception ex)
        {
            _= MessageService.Error($"执行SQL时出错: {ex.Message}");
        }
        finally
        {
            _loading = false;

        }
    }

    /// <summary>
    /// 重置所有加载状态
    /// </summary>
    public void ResetLoadingStates()
    {
        _loading = false;
        _loadingHistory = false;
        StateHasChanged();
    }

    /// <summary>
    /// 将SQL复制到剪贴板
    /// </summary>
    /// <param name="sql">要复制的SQL语句</param>
    /// <returns>异步任务</returns>
    private async Task CopySqlToClipboard(string sql)
    {
        if (string.IsNullOrEmpty(sql)) return;

        try
        {
            await JSRuntime.InvokeVoidAsync("navigator.clipboard.writeText", sql);
            _= MessageService.Success("SQL已复制到剪贴板");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"复制SQL失败: {ex.Message}");
            _= MessageService.Error("复制失败，请手动选择并复制");
        }
    }

    /// <summary>
    /// 初始化图表类型选项
    /// </summary>
    private void InitializeChartTypes()
    {
        _chartTypes = new List<ChartTypeOption>
        {
            new ChartTypeOption { Key = "bar", Label = "柱状图", Icon = "bar-chart" },
            new ChartTypeOption { Key = "line", Label = "折线图", Icon = "line-chart" },
            new ChartTypeOption { Key = "pie", Label = "饼图", Icon = "pie-chart" },
            new ChartTypeOption { Key = "scatter", Label = "散点图", Icon = "dot-chart" },
            new ChartTypeOption { Key = "area", Label = "面积图", Icon = "area-chart" }
        };
    }

    /// <summary>
    /// 初始化可用列选项
    /// </summary>
    private void InitializeAvailableColumns()
    {
        if (_currentChartMessage?.QueryResult == null || _currentChartMessage.QueryResult.Count == 0)
        {
            _availableColumns = new List<ColumnOption>();
            return;
        }

        try
        {
            _availableColumns = new List<ColumnOption>();
            
            // 获取所有列作为可选项
            var firstRow = _currentChartMessage.QueryResult.FirstOrDefault();
            if (firstRow != null)
            {
                foreach (var key in firstRow.Keys)
                {
                    var value = firstRow[key];
                    var isNumeric = IsNumericValue(value);
                    
                    _availableColumns.Add(new ColumnOption
                    {
                        Key = key,
                        Label = key,
                        Type = isNumeric ? "value" : "category"
                    });
                }
            }

            // 设置默认选择
            if (!_availableColumns.Any()) return;
            
            var categoryCol = _availableColumns.FirstOrDefault(c => c.Type == "category");
            var valueCol = _availableColumns.FirstOrDefault(c => c.Type == "value");
            
            _selectedCategoryColumn = categoryCol?.Key ?? _availableColumns.First().Key;
            _selectedValueColumns = valueCol != null ? new[] { valueCol.Key } : new[] { _availableColumns.Last().Key };
        }
        catch (Exception ex)
        {
            Console.WriteLine($"初始化列选项失败: {ex.Message}");
            _availableColumns = new List<ColumnOption>();
        }
    }

    /// <summary>
    /// 判断值是否为数值类型
    /// </summary>
    private bool IsNumericValue(object? value)
    {
        if (value == null) return false;
        
        return value is int or long or decimal or double or float or byte or short or uint or ulong or ushort or sbyte ||
               (value is string str && !string.IsNullOrWhiteSpace(str) && 
                (decimal.TryParse(str, out _) || double.TryParse(str, out _)));
    }

    /// <summary>
    /// 图表类型变更处理
    /// </summary>
    private async Task OnChartTypeChanged(ChartTypeOption chartType)
    {
        if (chartType == null) return;

        _selectedChartType = chartType.Key;
        await UpdateChart();
    }

    /// <summary>
    /// 列选择变更处理
    /// </summary>
    private async Task OnColumnSelectionChanged(ColumnOption column)
    {
        if (column == null) return;
        await UpdateChart();
    }

    /// <summary>
    /// 数值列选择变更处理
    /// </summary>
    private async Task OnValueColumnsChanged(IEnumerable<ColumnOption> columns)
    {
        _selectedValueColumns = columns?.Select(c => c.Key) ?? new List<string>();
        await UpdateChart();
    }

    /// <summary>
    /// 更新图表显示
    /// </summary>
    private async Task UpdateChart()
    {
        if (_currentChartMessage?.QueryResult == null || _currentChartMessage.QueryResult.Count == 0)
            return;

        try
        {
            var valueColumns = _selectedValueColumns.ToArray();
            if (valueColumns.Length == 0)
            {
                // 如果没有选择数值列，使用默认的第一个数值列
                var defaultValueCol = _availableColumns.FirstOrDefault(c => c.Type == "value");
                if (defaultValueCol != null)
                {
                    valueColumns = new[] { defaultValueCol.Key };
                    _selectedValueColumns = valueColumns;
                }
            }

            await JSRuntime.InvokeVoidAsync("echartsInterop.renderCustomChart", 
                "chatChartContainer", 
                _currentChartMessage.QueryResult,
                _selectedChartType,
                _selectedCategoryColumn,
                valueColumns);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"更新图表失败: {ex.Message}");
            _ = MessageService.Error("更新图表失败");
        }
    }

    /// <summary>
    /// 重置为自动图表
    /// </summary>
    private async Task ResetChartToAuto()
    {
        if (_currentChartMessage?.QueryResult == null || _currentChartMessage.QueryResult.Count == 0)
            return;

        try
        {
            await JSRuntime.InvokeVoidAsync("echartsInterop.renderAutoChart", "chatChartContainer", _currentChartMessage.QueryResult);
            
            // 重置选择状态
            InitializeAvailableColumns();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"重置图表失败: {ex.Message}");
            _ = MessageService.Error("重置图表失败");
        }
    }

    /// <summary>
    /// 为特定消息显示图表
    /// </summary>
    /// <param name="message">包含查询结果的消息</param>
    private async Task ShowChartForMessage(ChatMessage message)
    {
        if (message?.QueryResult == null || message.QueryResult.Count == 0)
        {
            _= MessageService.Info("暂无可视化数据");
            return;
        }

        _currentChartMessage = message;
        _isChartModalVisible = true;
        
        // 初始化列选项
        InitializeAvailableColumns();
        
        await InvokeAsync(StateHasChanged);

        try
        {
            await Task.Delay(300); // 等待DOM渲染和模态框动画完成
            await JSRuntime.InvokeVoidAsync("echartsInterop.renderAutoChart", "chatChartContainer", message.QueryResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"渲染图表失败: {ex.Message}");
            _= MessageService.Error("渲染图表失败");
        }
    }

    private async Task OnChartOk()
    {
        await OnChartCancel();
    }

    private async Task OnChartCancel()
    {
        _isChartModalVisible = false;
        _currentChartMessage = null;
        
        // 重置图表控制状态
        _availableColumns.Clear();
        _selectedCategoryColumn = null;
        _selectedValueColumns = new List<string>();
        _selectedChartType = "bar";
        
        try
        {
            await JSRuntime.InvokeVoidAsync("echartsInterop.dispose", "chatChartContainer");
        }
        catch { }
    }

    private async Task ExportChartPng()
    {
        try
        {
            await JSRuntime.InvokeVoidAsync("echartsInterop.exportPng", "chatChartContainer");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"导出失败: {ex.Message}");
            _= MessageService.Error("导出失败");
        }
    }

    /// <summary>
    /// 显示清空确认对话框
    /// </summary>
    private void ShowClearConfirm()
    {
        _isClearConfirmVisible = true;
    }

    /// <summary>
    /// 清空聊天记录
    /// </summary>
    private async Task ClearChatHistory()
    {
        if (string.IsNullOrEmpty(_selectedConnectionId))
        {
            return;
        }

        try
        {
            _clearingHistory = true;
            
            var success = await ChatService.ClearChatHistoryAsync(_selectedConnectionId);
            
            if (success)
            {
                _chatHistory.Clear();
                _= MessageService.Success("聊天记录已清空");
            }
            else
            {
                _= MessageService.Error("清空失败，请重试");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"清空聊天记录失败: {ex.Message}");
            _= MessageService.Error($"清空失败：{ex.Message}");
        }
        finally
        {
            _clearingHistory = false;
            _isClearConfirmVisible = false;
        }
    }
}